package com.boomsecret.juc.executor;

import org.eclipse.jetty.util.BlockingArrayQueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/22.
 */
public class ExecutorCompletionServiceDemo02 {
    public static void main(String[] args) {
        int corePoolSize = 1;
        int maximumPoolSize = 1;
        long keepAliveTime = 0L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new BlockingArrayQueue<>(32);
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler);

        ExecutorCompletionService service = new ExecutorCompletionService(threadPoolExecutor);
        for (int index = 1; index < 2; index ++) {
            int temp = index;
            service.submit(new Callable() {
                @Override
                public String call() throws Exception {
                    System.out.println("future start");
                    TimeUnit.SECONDS.sleep(temp + 2);
                    System.out.println("future end");
                    return "future response " + temp;
                }
            });
        }
        System.out.println("submit end");
        try {
            // 阻塞方法
            System.out.println(service.take().isDone());
//            service.poll()可能为空吧
//            System.out.println(service.poll().get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
        System.out.println("main end");
    }
}
